/**
 * Copyright (c) 2010 Claudio Imbrenda.
 * This program is released under the terms of the GNU GPL License, version 3 or later.
 */

#include <stdlib.h>
#include <stdio.h>

static void usage(){
 fprintf(stderr,"usage:\n\t graph2binary inputfile outputfile\n\n");
}

static void fail(char*m){
 fprintf(stderr,"Fatal error: %s\n",m);
 exit(1);
}

/** Converts a graph in text format into binary format.
*/
int main(int argc, char*argv[]){
 FILE*inf,*outf;
 unsigned int nnodes;
 unsigned int a,b,cx;
 
 if(argc!=3){
  usage();
  return 1;
 }

 /* open the input file */ 
 inf=fopen(argv[1],"r");
 if(inf==NULL)fail("cannot open input file.");
 
 /* open the output file*/
 outf=fopen(argv[2],"wb");
 if(outf==NULL)fail("cannot open output file.");
 
 if(fscanf(inf,"%u\n$",&nnodes)==EOF)fail("Wrong file format.");
 
 /* read the nodes count */
 fwrite(&nnodes,sizeof(int),1,outf);
 
 /* read the grades of nodes */
 for(cx=0;cx<nnodes;cx++){
  if(fscanf(inf,"%u %u\n",&a,&b)==EOF)fail("Wrong file format.");
  fwrite(&a,sizeof(int),1,outf);
  fwrite(&b,sizeof(int),1,outf);
 }
 
 /* reads the edges */
 while((cx=fscanf(inf,"%u %u\n",&a,&b))!=EOF){
  if(cx!=2)fail("Wrong file format.");
  fwrite(&a,sizeof(int),1,outf);
  fwrite(&b,sizeof(int),1,outf); 
 }

 /* closes all opened files */
 fflush(outf);
 fclose(inf);
 fclose(outf);
 return 0;
}
